<template>
  <div v-if="isShow">
    <h3>Counter A: {{ adc.countA }}</h3>
    <h3>Counter B: {{ adc.countB }}</h3>
    <button @click="adc.incrementA">Increment A</button>
    <button @click="adc.incrementB">Increment B</button>
    <button @click="stopScope">Stop Scope</button>
  </div>
</template>

<script setup>
import { ref, effectScope, onScopeDispose, reactive } from 'vue'

let scope // 用于存储 effectScope 实例

const isShow = ref(false)

// 创建 effectScope 作用域
function setupScope() {
  scope = effectScope() // 创建一个新的作用域

  return new Promise((resolve, reject) => {
    // 在该作用域中运行所有的响应式状态
    scope.run(() => {
      const countA = ref(0)
      const countB = ref(0)

      const incrementA = () => countA.value++
      const incrementB = () => countB.value++

      // 注册一个清理回调，当作用域被停止时调用
      onScopeDispose(() => {
        console.log('Scope disposed, cleaning up...')
      })

      // 返回需要在模板中使用的状态
      resolve({
        countA,
        countB,
        incrementA,
        incrementB
      })
    })
  })
}

let adc

const initScope = async () => {
  // 调用 setupScope，初始化作用域中的状态
  const { countA, countB, incrementA, incrementB } = await setupScope()

  adc = reactive({ countA, countB, incrementA, incrementB })
  console.log(countA)
  isShow.value = true
}
initScope()
// 停止作用域的函数
function stopScope() {
  if (scope) {
    scope.stop() // 停止作用域并触发销毁回调
  }
}
</script>
